package com.labofjet.system.generator.task;

import com.labofjet.system.constant.CRedisCacheConstant;
import com.labofjet.system.generator.context.TaskContext;
import com.labofjet.system.util.FreeMarkerUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 用freemarker处理file
 */
public abstract class FileStringGeneratorTask implements Task {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileStringGeneratorTask.class);


    @Override
    public boolean doTask(TaskContext c) {
        String fileString = "";
        String result = "";

        fileString = this.getFileString(); // 获取file的str形式
        result = FreeMarkerUtil.getProcessValue(c.getContext(), fileString); // process
        afterFileProcess(c, result); // 大概要设置到哪里去吧

        return true;
    }

    /**
     * file的String形式
     *
     * @return
     */
    protected String getFileString() {
        String fileString = "";
        try {
            ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resourceResolver.getResources("classpath*:/template/code/" + this.getTemplateRelativePath());
            fileString = IOUtils.toString(resources[0].getInputStream(), "UTF-8");
        } catch (IOException e) {
            LOGGER.error("获取模板错误", e);
            throw new RuntimeException(e);
        }
        return fileString;
    }

    /**
     * template的相对路径,相对于/template/code/
     *
     * @return
     */
    protected abstract String getTemplateRelativePath();

    /**
     * 处理完以后的字符串
     *
     * @return
     */
    protected abstract void afterFileProcess(TaskContext c, String result);
}
